<?php

namespace App\Http\ControllersVer1;

use Illuminate\Http\Request;

use Requests;

use Qiniu\Auth as QiniuAuth;
use Qiniu\Storage\UploadManager;

use Uuid;

use App\Book;
use App\User;
use App\BookImage;
use App\Appointment;

class BookController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * GET
     */
    public function showBook(Request $request, $book_uuid) {

        if (strlen($book_uuid) != 32) {
            return response()->json([
                'code' => 4060,
                'msg' => 'wrong book uuid!'
            ]);
        }

        $book = Book::where('uuid', $book_uuid)->first();

        if (is_null($book)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'no book!'
            ]);
        }

        $ongoing_appointment = Appointment::where('book_id', $book->id)
            ->whereIn('status', ['os', 'ap'])
            ->first();

        $finished_appointments = Appointment::where([
                ['book_id', $book->id],
                ['status', 'fs']
            ])
            ->orderBy('updated_at', 'desc')
            ->take(10)
            ->get();

        return response()->json([
            'code' => 2000,
            'book' => $book,
            'ongoing_appointment' => $ongoing_appointment,
            'finished_appointments' => $finished_appointments,
            'msg' => 'success!'
        ]);

    }


    /**
     * @param Request $request
     * @param $book_uuid
     */
    public function showBookCode(Request $request, $book_uuid) {
        //
        if (strlen($book_uuid) != 32) {
            return response()->json([
                'code' => 4060,
                'msg' => 'wrong book uuid!'
            ]);
        }

        $book = Book::where('uuid', $book_uuid)->first();

        if (is_null($book)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'no book!'
            ]);
        }

        $me = $request->user();
        if ($book->holder_id != $me->id) {
            return response()->json([
                'code' => 4060,
                'msg' => 'you are not the book holder.'
            ]);
        }

        //SkyLibrary
        $app_id = 'wx03d5b8742cdab615';
        $app_secret = '10e799067b4f21444a32e615c66cd06e';

        $url = "https://api.weixin.qq.com/cgi-bin/token";
        $url .= "?grant_type=client_credential";
        $url .= "&appid=".$app_id;
        $url .= "&secret=".$app_secret;

        $response = Requests::get($url);

        $ret_array = json_decode($response->body, true);

        if (array_key_exists('errcode', $ret_array)) {
            //
            return response()->json([
                'code' => 40600,
                'msg' => $ret_array['errmsg']
            ]);
        }

        $access_token = $ret_array['access_token'];

        //
        $url = "http://api.weixin.qq.com/wxa/getwxacodeunlimit";
        $url .= "?access_token=".$access_token;
        $headers = array('Content-Type' => 'application/json');
        $data = [
            'scene' => $book->uuid
        ];
        $response = Requests::post($url, $headers, json_encode($data));

        return response($response->body)
            ->withHeaders($response->headers->getAll());
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function createBook(Request $request) {

        $this->validate($request, [
            'image' => 'required|mimes:jpeg,png',
            //'book_isbn' => 'required|integer',
            'book_title' => 'required|max:100'
        ]);

        //$book_isbn = $request->input('book_isbn');
        $book_title = $request->input('book_title');

        if (!$request->hasFile('image')) {
            //
            return response()->json([
                'code' => 4060,
                'msg' => 'no photo file'
            ]);
        }

        //
        if (!$request->file('image')->isValid()) {
            //
            return response()->json([
                'code' => 4060,
                'msg' => 'photo upload is not valid.'
            ]);
        }


        //
        //$ext = $request->file('image')->getClientOriginalExtension();

        $access_key = 'D5r1vUBg8Xc5UjdVYorZRdHMpvaONPrgxcyyqHxn';
        $secret_key = 'A5c7sTC7nooJCJ8YV-HOmoJFO0Wu1JuLudcWtMvF';

        $auth = new QiniuAuth($access_key, $secret_key);
        $bucket = 'xreacting';
        $upload_token = $auth->uploadToken($bucket);

        // 要上传文件的本地路径
        $file_path = $request->file('image');

        // 上传到七牛后保存的文件名
        //todo: uuid for image
        $key = str_replace('-', '', Uuid::generate(4)->string);

        // 初始化 UploadManager 对象并进行文件的上传
        $upload_mgr = new UploadManager();


        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($upload_ret, $upload_err) = $upload_mgr->putFile($upload_token, $key, $file_path);

        if (is_null($upload_ret)) {

            return response()->json([
                'code' => 4060,
                'msg' => 'upload image failed.'
            ]);
        }

        if ($upload_ret['key'] != $key) {

            return response()->json([
                'code' => 4060,
                'msg' => 'upload ret key is wrong'
            ]);
        }

        $me = $request->user();

        $book = new Book;
        $book->uuid = str_replace('-', '', Uuid::generate(4)->string);
        $book->giver_id = $me->id;
        $book->holder_id = $me->id;
        //$book->isbn = $book_isbn;
        $book->title = $book_title;
        $book->story = '';
        $book->status = "1"; //todo: delete this.(status = 0 by default, and need to approve to be 1.)
        $book->save();


        //BookImage::where('book_id', $book->id)->delete();
        $book_image = new BookImage;
        $book_image->book_id = $book->id;
        $book_image->uuid = $key;
        $book_image->cloud = "Qiniu";
        $book_image->bucket = $bucket;
        $book_image->save();

        //$book = Book::find($book->id);

        return response()->json([
            'code' => 2000,
            'book_uuid' => $book->uuid,
            'msg' => 'fly book success.'
        ]);
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteBook(Request $request) {

        $this->validate($request, [
            'book_uuid' => 'required'
        ]);

        $book_uuid = $request->input('book_uuid');

        $book = Book::where('uuid', $book_uuid)->first();

        if (is_null($book)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'wrong book uuid!'
            ]);
        }

        $me = $request->user();

        if ($book->giver_id != $me->id) {
            //
            return response()->json([
                'code' => 4060,
                'msg' => 'you are not the book giver!'
            ]);
        }

        if ($book->holder_id != $me->id) {
            //
            return response()->json([
                'code' => 4060,
                'msg' => 'the book can not be deleted when you are not the holder!'
            ]);
        }


        $ongoing_appointment = Appointment::where([
            ['book_id', $book->id],
            ['status', '<>', 'fb']
        ])->first();

        if (!is_null($ongoing_appointment)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'there is ongoing appointment. you can not delete the book.'
            ]);
        }

        //delete the appointments for this book
        Appointment::where('book_id', $book->id)->delete();
        //delete the book
        $book->delete();

        return response()->json([
            'code' => 2000,
            'msg' => 'success!'
        ]);

    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editBook(Request $request) {

        $this->validate($request, [
            'book_uuid' => 'required',
            'book_story' => 'required'
        ]);

        $book_uuid = $request->input('book_uuid');
        $book_story = $request->input('book_story');

        $book = Book::where('uuid', $book_uuid)->first();

        if (is_null($book)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'wrong book uuid!'
            ]);
        }

        $me = $request->user();

        if ($book->giver_id != $me->id) {
            //
            return response()->json([
                'code' => 4060,
                'msg' => 'you are not the book giver!'
            ]);
        }

        if ($book->holder_id != $me->id) {
            //
            return response()->json([
                'code' => 4060,
                'msg' => 'you are not the book holder'
            ]);
        }


        $book->story = $book_story;
        $book->save();

        return response()->json([
            'code' => 2000,
            'msg' => 'success!'
        ]);

    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function listNearbyBooks(Request $request) {

        //max_id = ? for loading more

        if ($request->has('book_title')) {
            //
            $book_title = $request->input('book_title');

            $books = Book::where('title', 'like', '%'.$book_title.'%')
                ->orderBy('updated_at', 'desc')
                ->take(100)
                ->get();

        } else {
            //the [] ids must in table
            $books = Book::whereIn('holder_id', [1,2,3,4,5])
                ->orderBy('updated_at', 'desc')
                ->take(10)
                ->get();

        }

        return response()->json([
            'code' => 2000,
            'books' => $books,
            'msg' => 'ok'
        ]);

    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function listAllBooks(Request $request) {

        $books = Book::where('status', '1')
            ->orderBy('updated_at', 'desc')
            ->take(10)
            ->get();

        return response()->json([
            'code' => 2000,
            'books' => $books,
            'msg' => 'ok'
        ]);

    }

}
